/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-23 13:07:43
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-25 14:56:50
 * @FilePath: \vue3_nuxt_demo\server\api\auth\register.post.ts
 * @Description: 登录接口
 */
import Joi from 'joi';
import md5 from 'md5';
import { getDB } from '@/server/utils/db';
import { responseJson } from '@/server/utils/helper';

/**
 * 1、获取数据
 * 2、数据校验
 * 3、密码加密
 * 4、判断账号是否注册
 * 5、创建账号
 */

export default defineEventHandler(
  async (event) => {
    // 获取请求体
    const body = await readBody(event);
    
    // 校验数据joi
    const schema = Joi.object({
      avatar: Joi.string(),
      nickname: Joi.string().required(),
      phone: Joi.string().pattern(/1\d{10}/),
      password: Joi.string().required()
    });

    // 校验请求体
    try {
      const value = await schema.validateAsync(body);
    }
    catch (error) {
      return responseJson(400, {
        success: false,
        msg: '请求参数错误',
        error: error
      });
    }

    // 密码加密MD5
    const salt = 'ueidfisgfilegfiff';
    const password = md5(md5(body.password) + salt);
    
    // 数据库交互
    const { find, close } = getDB();

    // 查询
    const con = find();

    try {
      // 查询数据库
      const [users] = await con.execute('select * from `users` where `phone`=?',[body.phone]);

      // 判断是否已存在
      if (users?.length > 0) {
        return responseJson(200, {
          success: false,
          msg: '账号已注册',
          data: []
        });
      }

      // 注册账号
      const [rows] = await con.execute('insert into `users` (`nickname`,`phone`,`password`) value (?, ?, ?)',[body.nickname, body.phone, password]);
      
      // 注册判断
      if (rows.affectedRows === 1){
        return responseJson(200, {
          success: true,
          msg: '注册成功',
          data: []
        });
      }
    }
    catch (error) {

      return responseJson(500, {
        success: false,
        msg: '服务器错误',
        error: error
      });
    }
    finally {
      // 释放连接
      // close();
    }
  }
);